# -*- coding: utf-8 -*-
import requests
import json
import uuid
import re
from pymongo import MongoClient
from urllib.parse import quote

"""
羿才教育APP-题库
账户：18023305550
密码：123456
"""


cookies = {'PHPSESSID': 'ojhopid59odbe3jtidkv8lhav5'}
userAgent = "Dalvik/2.1.0 (Linux; U; Android 5.1.1; HUAWEI MLA-AL10 Build/HUAWEIMLA-AL10)"
header = {
    "Accept-Encoding": "gzip",
    "Accept-Language": "zh-CN,zh;q=0.9",
    "Connection": "keep-alive",
    "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
    "Host": "api.tk160.com",
    'User-Agent': userAgent,
}

# 获取章节
def getPart(token, subjectId, productId):
    postData = {
        'token': token,
        'subjectId': subjectId, # '348',
        'productId': productId, # '585'
    }
    url = 'http://api.tk160.com/know/index'
    responseRes = requests.post(url, data = postData, headers = header, cookies = cookies)
    contents = json.loads(responseRes.content)
    product_info = contents['data']['product_info']['name'] # 科目名称
    subject_id = contents['data']['product_info']['subject_id']
    for k in contents['data']['subject_list']:
        subject_id = k['subject_id']
        if subjectId == subject_id:
            kemu = k['subject_name']
            break

    for t in contents['data']['know_list']:
        part = t['title']
        if len(t['children']) > 0:
            for t1 in t['children']:
                getContent(token, product_info, kemu, part, t1['title'], subjectId, productId, t1['id'])
        else:
            getContent(token, product_info, kemu, part, t['title'], subjectId, productId, t['id'])

# 获取题内容
def getContent(token, product_info, kemu, part, title, subjectId, productId, knowId):
    subject = ''
    postData = {
        'token': token,
        'subjectId': subjectId,
        'productId': productId,
        'knowId': knowId,
        'itemType': 0,
        'num': 100000,
        'again': 1,
        'type': 0,

    }
    url = 'http://api.tk160.com/know/getItemsList '
    responseRes = requests.post(url, data = postData, headers = header, cookies = cookies)
    if responseRes.status_code == 200:
        contents = json.loads(responseRes.content)

        for j in contents['data']['list']:
            detailDict = dict()

            detailDict['product_info'] = product_info   #标题一级
            detailDict['kemu'] = kemu   #科目二级标题
            detailDict['part_type'] = '章节练习'
            detailDict['part'] = part   #科目三级标题  章节
            detailDict['subject_id'] = subjectId   # 标题ID
            detailDict['name'] = title   # 四级章节名称
            # detailDict['paperId'] = paperId # 题目ID 第3级 标题-章-节
            subject_id = j['subject_id']    # 题号
            detailDict['type_id'] = j['type']    # 题类型号
            type_name = j['type_name']  # 题类型
            detailDict['pid'] = j['pid']  # 主题号
            detailDict['item_id'] = j['item_id']  # 次题号
            answerID = j['answer']    # 答案ID
            analysis = j['analysis']    # 参考答案
            print('标题：' + str(j['title']))
            print('参考答案：' + str(analysis))
            print('========' + product_info + '===========')
            print('=====待选=====')
            detailDict['subject_id'] = subject_id
            detailDict['type_name'] = type_name
            detailDict['main_title'] = j['main_title']  # 共享题干标题
            detailDict['title'] = j['title']    # 标题
            detailDict['title_tmp'] = str(j['main_title']) + '\r\n' + str(j['title'])
            detailDict['analysis'] = analysis
            num = 0
            answerContent = ''

            if type_name == '判断题':
                if j['answer'] == 1:
                    answerContent = '对'
                else:
                    answerContent = '错'
            elif j['type_name'] == '问答题':
                answerContent = j['answer']
            elif j['type_name'] == '单选题' or j['type_name'] == '多选题' or j['type_name'] == '不定项选择题':
                for op in j['options']:
                    num = num + 1
                    id = op['id']   # 待选答题ID
                    content = op['content'] # 待选答案
                    print(content)
                    detailDict['no_' + str(num)] = id
                    detailDict['content_' + str(num)] = content
                    # tmpAnswerID = answerID.split(',')
                    # for tt in tmpAnswerID:
                    #     if tt == id:
                    #         answerContent = answerContent + ' ' + content
                    if answerID.find(id) >= 0:
                        answerContent = answerContent + ' ' + re.sub('[^a-zA-Z].*', '', content, flags=re.M | re.S)
            else:
                answerContent = j['answer']

            print('【题型】：' + str(j['type_name']))
            print('【正确答案】：' + str(answerContent))
            detailDict['answerContent'] = answerContent
            insertItem(productType + product_info, detailDict)

    conn.close()


# 获取题内容模拟
def getMN(token, subjectId, recordsType, productId):
    subject = ''
    postData = {
        'token': token,
        'subjectId': subjectId,  #'46',
        'recordsType': recordsType,  # '2',
        'limit': '100000',
        'productId': productId,  # '853',
    }
    url = 'http://api.tk160.com/paper/index'
    responseRes = requests.post(url, data=postData, headers=header, cookies = cookies)
    if responseRes.status_code == 200:
        contents = json.loads(responseRes.content)
        product_info = contents['data']['product_info']['name'] # 科目名称
        # subject_id = contents['data']['product_info']['subject_id']
        for k in contents['data']['subject_list']:
            subject_id = k['subject_id']
            if subjectId == subject_id:
                kemu = k['subject_name']
                tmpDict = k['child']
                break

        for j in contents['data']['paper_list']['data']:
            for kk in tmpDict:
                if kk['id'] == j['type']:
                    part = kk['name']
                    break
            getMN1(token, subjectId, recordsType, kemu, part, productId, j['id'], product_info, j['name'])



    conn.close()

# 获取题内容模拟
def getMN1(token, subjectId, recordsType, kemu, part, productId, paperId, product_info, name):
    subject = ''
    postData = {
        'token': token,
        'subjectId': subjectId,# '46',
        'recordsType': recordsType, # '2',
        'limit': '100000',
        'productId': productId, # '853',
        'paperId': paperId,
    }
    url = 'http://api.tk160.com/paper/itemsList'
    responseRes = requests.post(url, data=postData, headers=header, cookies=cookies)
    if responseRes.status_code == 200:
        contents = json.loads(responseRes.content)

        for j in contents['data']['list']:
            detailDict = dict()

            detailDict['kemu'] = kemu
            detailDict['part_type'] = part
            detailDict['part'] = part   #科目三级标题  章节
            detailDict['paperId'] = paperId
            detailDict['product_info'] = product_info   #标题一级
            detailDict['subject_id'] = subjectId   # 标题ID
            detailDict['name'] = name   # 三级章节名称
            detailDict['paperId'] = paperId # 题目ID 第3级 标题-章-节
            subject_id = j['subject_id']    # 题号
            title = j['title']  # 标题
            detailDict['type_id'] = j['type']    # 题类型号
            detailDict['pid'] = j['pid']  # 主题号
            detailDict['item_id'] = j['item_id']  # 次题号
            answerID = j['answer']    # 答案ID
            analysis = j['analysis']    # 参考答案
            print('标题：' + str(j['title']))
            print('参考答案：' + str(analysis))
            print('========' + product_info + '===========')
            print('=====待选=====')
            detailDict['subject_id'] = subject_id
            detailDict['type_name'] = j['type_name'] # 题类型
            detailDict['main_title'] = j['main_title'] # 共享题干标题
            detailDict['title'] = j['title']    # 标题
            detailDict['title_tmp'] = str(j['main_title']) + '\r\n' + str(j['title'])
            detailDict['analysis'] = analysis

            num = 0
            answerContent = ''
            if j['type_name'] == '判断题':
                if j['answer'] == 1:
                    answerContent = '对'
                else:
                    answerContent = '错'
            elif j['type_name'] == '问答题':
                answerContent = j['answer']
            elif j['type_name'] == '单选题' or j['type_name'] == '多选题' or j['type_name'] == '不定项选择题':
                for op in j['options']:
                    num = num + 1
                    id = op['id']   # 待选答题ID
                    content = op['content'] # 待选答案
                    print(content)
                    detailDict['no_' + str(num)] = id
                    detailDict['content_' + str(num)] = content
                    # tmpAnswerID = answerID.split(',')
                    # for tt in tmpAnswerID:
                    #     if tt == id:
                    #         answerContent = answerContent + ' ' + content
                    if answerID.find(id) >= 0:
                        answerContent = answerContent + ' ' + re.sub('[^a-zA-Z].*', '', content, flags=re.M | re.S)
            else:
                answerContent = j['answer']

            print('【题型】：' + str(j['type_name']))
            print('【正确答案】：' + str(answerContent))
            detailDict['answerContent'] = answerContent
            insertItem(productType + product_info, detailDict)

    conn.close()

# 获取题库id
def getTitle(keyword):
    postData = {
        'page': 1, # '348',
        'type': 'question', # '585'
        'limit': '6', # '585'
        'keyword': keyword # '585'

    }
    url = 'http://api.tk160.com/index/search'
    responseRes = requests.post(url, data = postData, headers = header, cookies = cookies)
    contents = json.loads(responseRes.content)
    product_info = contents['data']['data']['question'] # 科目名称
    tmp = ''

    tmpId = ''
    arryTmp = []

    for k in product_info:
        productId = k['id']
        subjectId = k['subjects']
        tmpId = k['id']
        print('====name====' + k['name'])
        print('===productId====' + k['id'])

    for t in subjectId:
        arryTmp.append(t['id'])
        tmp = tmp + ', ' + '\'' + t['id'] + '\''
        print('===subjectId====' + t['id'])
    print(tmp)
    return tmpId, arryTmp

# 获取视频
def getVideoId(keyword):
    postData = {
        'page': 1, # '348',
        'type': 'course', # '585'
        'limit': '6', # '585'
        'keyword': keyword # '585'

    }
    url = 'http://api.tk160.com/index/search'
    responseRes = requests.post(url, data = postData, headers = header, cookies = cookies)
    contents = json.loads(responseRes.content)
    product_info = contents['data']['data']['course'] # 科目名称

    for k in product_info:
        target_id = k['target_id']
        name = k['name']
        print('====target_id====' + k['target_id'])
        print('===name====' + k['name'])
    return target_id, name

def getVideoUrl(target_id):
    postData = {
        'type': 'package', # '585'
        'id': target_id # '585'

    }
    url = 'http://api.tk160.com/course/show'
    responseRes = requests.post(url, data = postData, headers = header, cookies = cookies)
    contents = json.loads(responseRes.content)
    product_info = contents['data']['selectData']
    title = contents['data']['info']['name']
    for k in product_info:
        kemu = k['name']
        for t in k['classes']:
            classname = t['name']
            classid = t['id']
            getVideoUrl1(title, kemu, classname, target_id , classid)
def getVideoUrl1(title, kemu, classname, id, classId):
    postData = {
        'type': 'package',
        'id': id ,
        'classId': classId
    }
    url = 'http://api.tk160.com/course/show'
    responseRes = requests.post(url, data = postData, headers = header, cookies = cookies)
    contents = json.loads(responseRes.content)
    product_info = contents['data']

    for k in product_info['lessons']:
        detailDict = dict()

        detailDict['title'] = title
        detailDict['kemu'] = kemu
        detailDict['classname'] = classname
        detailDict['type'] = k['name']
        detailDict['url'] = k['video']
        insertItem('VideoUrl', detailDict)


def insertItem(tableName, data):
    my_set = db[tableName]
    my_set.insert_one(data)


if __name__ == "__main__":
    conn = MongoClient('127.0.0.1', 27017)
    db = conn["Medical"]
    token = 'f5bb770aada73d274a5e35cf65dab4d9'
    productType = 'bbb_'
    titleTmp = [
                '2020年初级管理会计师（全套四科-普通版）考试题库',

            ]

    # 获取题库
    for ti in titleTmp:
        try:
            # 获取productId、subjectId
            Id, arryTmp = getTitle(ti)
            productId = Id # '603' #
            tmp = arryTmp # ['366']
            recordsType = '2'
            for t in tmp:
                getPart(token, t, productId)
                recordsType = '2'
                getMN(token, t, recordsType, productId)
        except Exception as e:
            print('=========异常============')
            print(e)
            print('科目名称:' + ti)
            print('productId:' + productId)
            print('subjectId:' + t)
            break
        else:
            print('========结束===========')

    # # 获取视频地址
    # for tt in titleTmp:
    #     try:
    #
    #         id, name = getVideoId(tt)
    #
    #         getVideoUrl(id)
    #     except Exception as e:
    #         print('=========异常============')
    #         print(e)
    #         print('科目名称:' + tt)
    #     else:
    #         print('========结束===========')
    # # 获取视频地址


